<template>
<div class="quickReply flex-column">
  <div class="quickReplyTitle" v-if="title">{{title}}</div>
  <div class="addQuickReply" v-if="btnsTop">
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('text')"
    @click="showQuickReplyDialog('text')">
      <i class="layui-icon layui-icon-add-1"></i>
      文本
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('link')"
    @click="showQuickReplyDialog('link')">
      <i class="layui-icon layui-icon-add-1"></i>
      链接
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('image')"
    @click="showQuickReplyDialog('image')">
      <i class="layui-icon layui-icon-add-1"></i>
      图片
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('video')"
    @click="showQuickReplyDialog('video')">
      <i class="layui-icon layui-icon-add-1"></i>
      视频
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('contact')"
    @click="showQuickReplyDialog('contact')">
      <i class="layui-icon layui-icon-add-1"></i>
      名片
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('officalAccount')"
    @click="showQuickReplyDialog('officalAccount')">
      <i class="layui-icon layui-icon-add-1"></i>
      公众号
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('documents')"
    @click="showQuickReplyDialog('documents')">
      <i class="layui-icon layui-icon-add-1"></i>
      材料库
    </button>
  </div>
  <div class="quickReplies" v-if="showReplies">
    <message
      v-for="(reply, i) in replies"
      :reply="reply"
      :active="currentReply && currentReply.localid == reply.localid"
      @click="chooseReply(reply)"
      @delete="deleteReplyLocal(reply)"
      :key="i">
    </message>
  </div>
  <div class="addQuickReply" v-if="!btnsTop">
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('text')"
    @click="showQuickReplyDialog('text')">
      <i class="layui-icon layui-icon-add-1"></i>
      文本
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('link')"
    @click="showQuickReplyDialog('link')">
      <i class="layui-icon layui-icon-add-1"></i>
      链接
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('image')"
    @click="showQuickReplyDialog('image')">
      <i class="layui-icon layui-icon-add-1"></i>
      图片
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('video')"
    @click="showQuickReplyDialog('video')">
      <i class="layui-icon layui-icon-add-1"></i>
      视频
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('contact')"
    @click="showQuickReplyDialog('contact')">
      <i class="layui-icon layui-icon-add-1"></i>
      名片
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('officalAccount')"
    @click="showQuickReplyDialog('officalAccount')">
      <i class="layui-icon layui-icon-add-1"></i>
      公众号
    </button>
    <button class="layui-btn layui-btn-xs"
    v-if="types.includes('documents')"
    @click="showQuickReplyDialog('documents')">
      材料库
    </button>
  </div>
  <div class="textQuickReplyDialog flex-column"
    v-if="showDialog && dialogType == 'textQuickReply'">
    <div class="dialogHead flex-row">
      <div class="editServiceTitle">添加文本</div>
      <i class="layui-icon layui-icon-close pointer" @click="()=>this.showDialog=false"></i>
    </div>
    <div class="editForm flex-column">
      <div class="editFormItem">
        <rich-text-editor
          :placeholder="textPlaceHolder"
          :withButton="false"
          ref="editor"></rich-text-editor>
        <!-- <textarea v-model="form.textQuickReply" ></textarea> -->
      </div>
      <button class="layui-btn layui-btn-normal submitInfo" @click="addQucikReply(dialogType)">确定</button>
    </div>
  </div>
  <div class="linkQuickReplyDialog flex-column"
    v-if="showDialog && dialogType == 'linkQuickReply'">
    <div class="dialogHead flex-row">
      <div class="editServiceTitle">添加链接</div>
      <i class="layui-icon layui-icon-close pointer" @click="()=>this.showDialog=false"></i>
    </div>
    <div class="editForm flex-column">
      <div class="editFormItem">
        <input type="text" placeholder="请输入链接地址(必填)" @change="changeForm('linkQuickReply', 'url', $event.target.value)" :value="form.linkQuickReply ? form.linkQuickReply.url : ''">
      </div>
      <div class="editFormItem">
        <input type="text" placeholder="请输入标题(必填)" @change="changeForm('linkQuickReply', 'title', $event.target.value)" :value="form.linkQuickReply ? form.linkQuickReply.title : ''">
      </div>
      <div class="editFormItem flex-row avatarEdit">
        <div style="width:40px;height:40px;background:#eee">
          <img v-if="form.linkQuickReply && form.linkQuickReply.src ? form.linkQuickReply.src : ''" :src="form.linkQuickReply && form.linkQuickReply.src ? form.linkQuickReply.src : ''">
        </div>
        <input type="text" placeholder="请输入网络图地址" @input="changeForm('linkQuickReply', 'src', $event.target.value)"  :value="form.linkQuickReply ? form.linkQuickReply.src : ''" />
      </div>
      <div class="editFormItem">
        <textarea  placeholder="请输入简介内容" @change="changeForm('linkQuickReply', 'content', $event.target.value)" :value="form.linkQuickReply ? form.linkQuickReply.content : ''"></textarea>
      </div>
      <button class="layui-btn layui-btn-normal submitInfo" @click="addQucikReply(dialogType)">确定</button>
    </div>
  </div>
  <div class="imageQuickReplyDialog flex-column"
    v-if="showDialog && dialogType == 'imageQuickReply'">
    <div class="dialogHead flex-row">
      <div class="editServiceTitle">添加图片</div>
      <i class="layui-icon layui-icon-close pointer" @click="()=>this.showDialog=false"></i>
    </div>
    <div class="editForm flex-column">
      <div class="editFormItem flex-column">
        <div style="width:120px;height:120px;background: #ccc;">
          <img v-if="form.imageQuickReply && form.imageQuickReply.tempUrl ? form.imageQuickReply.tempUrl : ''" :src="form.imageQuickReply && form.imageQuickReply.tempUrl ? form.imageQuickReply.tempUrl : ''">
        </div> 
        <span class="clickedSpan">
          <slot v-if="!uploading">
            上传图片
            <input type="file" accept=".png, .jpg, .jpeg" @change="changeForm('imageQuickReply', 'avatar', $event.target.value, $event)">
          </slot>
          <slot v-if="uploading">
            正在上传... {{progress}}%
          </slot>
        </span>
      </div>
      <button class="layui-btn layui-btn-normal submitInfo" @click="addQucikReply(dialogType)">确定</button>
    </div>
  </div>
  <div class="videoQuickReplyDialog flex-column"
    v-if="showDialog && dialogType == 'videoQuickReply'">
    <div class="dialogHead flex-row">
      <div class="editServiceTitle">添加视频</div>
      <i class="layui-icon layui-icon-close pointer" @click="()=>this.showDialog=false"></i>
    </div>
    <div class="editForm flex-column">
      <div class="editFormItem flex-column">
        <video
          autoplay
          :controls="form.videoQuickReply && form.videoQuickReply.tempUrl ? true : false"
          :src="form.videoQuickReply && form.videoQuickReply.tempUrl ? form.videoQuickReply.tempUrl : ''" />
        <span class="clickedSpan">
          <slot v-if="!uploading">
            上传视频
            <input type="file" accept=".mp4, .ogg, .webm" @change="changeForm('videoQuickReply', 'avatar', $event.target.value, $event)">
          </slot>
          <slot v-if="uploading">
            正在上传... {{progress}}%
          </slot>
        </span>
      </div>
      <button class="layui-btn layui-btn-normal submitInfo" @click="addQucikReply(dialogType)">确定</button>
    </div>
  </div>
  <div class="cardQuickReplyDialog flex-column"
    v-if="showDialog && (dialogType == 'contactQuickReply' || dialogType == 'officalAccountQuickReply')">
    <div class="dialogHead flex-row">
      <div class="editServiceTitle">添加名片</div>
      <i class="layui-icon layui-icon-close pointer" @click="()=>this.showDialog=false"></i>
    </div>
    <div class="editForm flex-column">
      <div class="editFormItem flex-row">
        <input type="radio" name="gender" value="contact"
          :checked="dialogType == 'contactQuickReply'" disabled @change="changeForm(dialogType, 'type', $event.target.value)">好友名片
        <input type="radio" name="gender" value="officalAccount"
        :checked="dialogType == 'officalAccountQuickReply'" disabled @change="changeForm(dialogType, 'type', $event.target.value)">公众号名片
      </div>
      <div class="editFormItem">
        <input type="text" placeholder="请输入好友昵称或微信号" @input="changeForm(dialogType, 'keyword', $event.target.value)">
      </div>
      <div class="editFormItem flex-row cardInfo">
          <div :class="['userItem', 'flex-row', currentFriend&&currentFriend.wxid==user.wxid ? 'activeFriend' : '']"
           @click="setCurrentFriend(user)"
           v-for="user in filteredFriends" :key="user.wxid">
            <img :src="user.avatar" alt="">
            <div class="flex-column">
              <div class="editCardName textEllipsis">{{user.name}}</div>
              <div class="wxidInfo textEllipsis">
                <span class="fontGrey textEllipsis">{{user.wxid}}</span>
              </div>
            </div>
          </div>
      </div>
      <button class="layui-btn layui-btn-normal submitInfo" @click="addQucikReply(dialogType)">确定</button>
    </div>
  </div>
   <div class="documentsQuickReplyDialog flex-column"
    v-if="showDialog && dialogType == 'documentsQuickReply'">
    <div class="dialogHead flex-row">
      <div class="editServiceTitle">材料库</div>
      <i class="layui-icon layui-icon-close pointer" @click="()=>this.showDialog=false"></i>
    </div>
    <div class="editForm flex-column" ref="docScrollView" @scroll="docScroll">
      <div ref="docScroller">
        <div :key="i" v-for="(reply, i) in documents" class="flex-row documentsListItem autoGrow">
          <input type="checkbox" :value="reply.id" name="document" @change="selectDocument(reply)">
          <message
            :reply="reply" 
            @delete="deleteReply(reply)"
            >
          </message>
        </div>
      </div>
    </div>
    <button class="layui-btn layui-btn-normal layui-btn-sm submitInfo" @click="submitDocument">提交</button>
  </div>
</div>
</template>
<script>
import {mapState, mapMutations, mapActions} from 'vuex';
import RichTextEditor from '@/components/richTextEditor'
import Message from '@/components/message'
import { throttle } from '@/lib/utils'
export default {
  name: 'quickReplies',
  data() {
    return {
      uploading: false,
      progress: 0,
      showDialog: false,
      dialogType: '',
      currentReply: null,
      documents: [],
      documentsPage :{
        pageNo:1,
        pageSize:20,
        fetching:false
      },
      replies: [],
      friends: [],
      currentFriend: null,
      checkedDocument: {},
      form: {},
      msgTypeMap: {
        'text': 1,
        'link': 10,
        'image': 2,
        'contact': 13,
        'officialAccount': 13,
        'documents': 6,
        'video': 4
      }
    }
  },
  props: {
    title: {
      type: String,
      default: '快捷回复',
    },
    btnsTop: {
      type: Boolean,
      default: false
    },
    upToStore: {
      type: Boolean,
      default: true
    },
    showReplies: {
      type: Boolean,
      default: true
    },
    types: {
      type: Array,
      default() {
        return ['text', 'link', 'image', 'contact', 'officalAccount', 'documents']
      }
    },
    textPlaceHolder: {
      type: String,
      default: '请输入快捷回复'
    },
    initReply:{
      type:Array,
      default(){
        return []
      }
    }
  },
  created() {
    if(this.initReply)
      this.replies = this.replies.concat(this.initReply||[]) 
  },
  computed: {
    ...mapState(['manager', 'services','chatMap','uistate','accountMap']),
    filteredFriends() {
      const keyword = this.form.contactQuickReply ? this.form.contactQuickReply.keyword : ''
      if (keyword) {
        return this.friends.filter(f=>f.name.indexOf(keyword) > -1 || f.wxid == keyword)
      }
      return this.friends
    }
  },
  watch: {
    'manager.quickReplies': (val, oldVal) => {
      if (val.length && !oldVal.length) {
        this.replies = val;
      }
    },
    replies(){
      this.$emit('change',this.replies)
    }
  },
  methods: {
    ...mapMutations(['pushReply','addMessageMap','addMessageListMap']),
    ...mapActions(['wsSend']),
    showQuickReplyDialog(type) {
      if (type == 'contact') {
        this.initFriends()
      }else if(type === 'documents'){
        this.documentsPage.pageNo = 1
        this.getDocuments({  pageNo:1, pageSize:20 })
      }
      this.checkedDocument = {}
      this.form = {}
      this.showDialog = true;
      this.dialogType = `${type}QuickReply`;
    },
    setCurrentFriend(friend) {
      this.currentFriend = friend;
    },
    initFriends() {
      this.getServicesFriends(this.services).then(data=>{
        this.friends = data
      }).catch(e=>this.$msg(e))
    },
    getDocuments(params){
      const csid = this.uistate.csid
      if(this.documentsPage.fetching)return;
      this.documentsPage.fetching = true;
      return this.$api.phrase.getlimit({ csId:csid,...params }).then((data)=>{
        if(data){
          const replys = data.map(item=>{
            try {
              const rp = JSON.parse(item.msgextra)
              rp.id = item.id
              return rp  
            } catch (error) {
              return {}   
            }
          }) 
          if(params.pageNo === 1){
            this.documents = replys

          }else{
            this.documents.push(replys)
          }
          this.documentsPage = {
            pageNo:params.pageNo,
            pageSize:params.pageSize,
          }
        }
        this.documentsPage.fetching = false
        
      }).catch(e=>this.$msg(e))
    },
    initReplies() {

       
    },
    deleteReplyLocal(reply){
      this.replies = this.replies.filter(r=>r.localid != reply.localid);
    },
    deleteReply(reply) {
      this.deleteReplyLocal(reply)
      this.$api.phrase.del(reply).then((data)=>{
        this.documents = this.documents.filter(r=>r.id!==reply.id)
      }).catch(e=>this.$msg(e))

    },
    async addQucikReply(dialogType) {
      const type = /(\w+)QuickReply/g.exec(dialogType)[1];
      const data = this.form[dialogType];
      if (!data && type != 'text' && type != 'contact' && type != 'officialContact') {
        this.showDialog = false
        return
      }
      let reply
      try {
        if (type == 'text') {
          reply = {
            type,
            content: this.$refs.editor.getEditorValue()
          }
        } else if (type == 'link') {
          reply = {
            type,
            url: data.url,
            title: data.title,
            content: data.content,
            src: data.src,
            tempUrl: data.tempUrl
          }
        } else if (type == 'image') {
          this.uploading = true
          const src = await this.uploadFile(data.avatar, {
            onUploadProgress:({loaded, total}) =>{
              this.progress = Math.floor((loaded / total) * 100)
            },
            timeout: 30000
          })
          this.uploading = false
          reply = {
            type,
            src: src,
            tempUrl: data.tempUrl
          }
        } else if (type == 'video') {
          this.uploading = true
          const src = await this.uploadFile(data.avatar, {
            onUploadProgress:({loaded, total})=>{
              this.progress = Math.floor((loaded / total) * 100)
            },
            timeout: 30000
          })
          this.uploading = false
          reply = {
            type,
            src: src,
            tempUrl: data.tempUrl
          }
        }else if (type == 'contact') {
          if (!this.currentFriend) {
            return this.$msg("请选择要发送的好友名片")
          }
          reply = {
            type,
            src: this.currentFriend.avatar,
            title: this.currentFriend.name,
            wxid: this.currentFriend.wxid,
          }
        } else if (type == 'officalAccount') {
          reply = {
            type
          }
        }
      } catch(e) {
        this.uploading = false
        return this.$msg(e)
      }
      reply.msgtype = this.msgTypeMap[reply.type] || 1
      reply.localid = Date.now().toString();
      if (this.upToStore) {
        this.pushReply(reply);
      }
      
      this.setCurrentReply(reply)
      this.$emit('change', reply);
      this.showDialog = false;
      this.form = {}
      this.addPhrase(reply)
      

    },
    addPhrase(reply){
      const chatid = this.uistate.chatid
      const csid = this.uistate.csid
      // const chat = this.chatMap[chatid]
      // const { csid,wxaccount } = chat
      this.$api.phrase.add({
        csid, 
        msgtype:reply.msgtype,msgcontent:'',
        msgextra:JSON.stringify(reply)
      })
      .then(res=>{
        if(res){
          reply.id = res
          this.replies.push(reply)
        }
      })
    },
    changeForm(name, key, val, e) {
      let file, tempUrl;
      if (e && e.target && e.target.files) {
        file = e.target.files[0]
        tempUrl = window.URL.createObjectURL(file);
        return this.$set(this.form, name, {
          ...this.form[name],
          [key]: file,
          title: file.name,
          tempUrl
        })
      }
      this.$set(this.form, name, {
        ...this.form[name],
        [key]: val
      })
    },
    chooseReply(reply) {
      // reply.msgtype = this.msgTypeMap[reply.type] || 1
      // this.setCurrentReply(reply)
      // this.$emit('change', reply);
    },
   
    setCurrentReply(reply) {
      this.currentReply = reply
    },
    setDialogData(data) {
      const { type } = data
      this.$set(this.form, `${type}QuickReply`, data)
      if (type == 'text') {
        this.$nextTick(()=>{
          this.$refs.editor.setEditorValue(data.content)
        })
      }
    },
    selectDocument(reply) {
      const { id } = reply
      if(this.checkedDocument[id]){
        delete this.checkedDocument[id]
      }else{
        this.checkedDocument[id] = reply
      }
    },
    submitDocument() {
      if (!this.checkedDocument) {
        this.showDialog = false
        return
      }
      const checkedDocument = this.checkedDocument;
      const list = Object.keys(checkedDocument).map(key=>checkedDocument[key])
       
      const _replies = this.replies.map(item=>item.id) 
      list.forEach(item=>{
        if(!_replies.includes(item.id)){
          this.replies.push(item)
        }
      })
       
      this.showDialog = false
    },
    docEndreached(){
      this.getDocuments({ pageNo:this.documentsPage.pageNo+1,pageSize:this.documentsPage.pageSize }) 
    },
    docScroll:throttle(function(e){
      const scrollview = this.$refs['docScrollView']
      const scroller = this.$refs['docScroller']
      const { paddingTop,paddingBottom } = getComputedStyle(scrollview)
      
      if(scrollview.scrollTop+scrollview.offsetHeight+50 >= scroller.offsetHeight){
        this.docEndreached()
      }
    },200,{ leading:true }) 
  },
  components: {
    RichTextEditor,
    Message
  }
}
</script>
<style scoped>
.documentsQuickReplyDialog .editForm div{
  flex-shrink: inherit 
}
</style>